<template>
    <el-card class="w-full pt-[5px] pb0">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" label-width="96px">

        <el-form-item prop="checkStatus" class="ml-[-96px]">
            <el-radio-group v-model="queryParams.checkStatus" @change="handleQuery">
                <el-radio-button :label="'全部('+checkStatusCount.all+')'" value="" />
                <el-radio-button
                    v-show="dict.value > 0"
                    v-for="dict in bpm_process_instance_status"
                    :key="dict.value"
                    :label="dict.label+'('+(checkStatusCount[dict.value]?checkStatusCount[dict.value].checkStatusCount:0)+')'"
                    :value="dict.value"
                ></el-radio-button>
            </el-radio-group>
        </el-form-item>

        <el-row :gutter="20">
            <el-col :span="6">
                <el-form-item label="机构编号" prop="code">
                    <el-input
                    v-model="queryParams.code"
                    placeholder="请输入机构编号"
                    clearable
                    @keyup.enter="handleQuery"
                    />
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item label="机构名称" prop="name">
                    <el-input
                    v-model="queryParams.name"
                    placeholder="请输入机构名称"
                    clearable
                    @keyup.enter="handleQuery"
                    />
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item label="机构级别" prop="levelId">
                    <el-select v-model="queryParams.levelId" placeholder="请选择机构级别" clearable>
                        <el-option
                            v-for="dict in cfg_category_jgjb"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                        />
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <div class="flex justify-end"> 
                    <el-button type="primary" @click="searchFormOpen = !searchFormOpen"
                    >更多
                    <el-icon color="#fff">
                        <CaretTop v-show="searchFormOpen" />
                        <CaretBottom v-show="!searchFormOpen" />
                    </el-icon>
                    </el-button>
                    <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                    <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </div>
            </el-col>
        </el-row>
        
        <div v-show="searchFormOpen">
        <el-row :gutter="20">
            <el-col :span="6">
                <el-form-item label="负责人" prop="charger">
                    <el-input
                    v-model="queryParams.charger"
                    placeholder="请输入负责人"
                    clearable
                    @keyup.enter="handleQuery"
                    />
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item label="联系人" prop="contacts">
                    <el-input
                    v-model="queryParams.contacts"
                    placeholder="请输入联系人"
                    clearable
                    @keyup.enter="handleQuery"
                    />
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item label="电话" prop="tel">
                    <el-input
                    v-model="queryParams.tel"
                    placeholder="请输入电话"
                    clearable
                    @keyup.enter="handleQuery"
                    />
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item label="邮箱" prop="email">
                    <el-input
                    v-model="queryParams.email"
                    placeholder="请输入邮箱"
                    clearable
                    @keyup.enter="handleQuery"
                    />
                </el-form-item>
            </el-col>
        </el-row>

        <el-row :gutter="20">
            <el-col :span="6">
                <el-form-item label="传真" prop="fax">
                    <el-input
                    v-model="queryParams.fax"
                    placeholder="请输入传真"
                    clearable
                    @keyup.enter="handleQuery"
                    />
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item label="地址" prop="address">
                    <el-input
                    v-model="queryParams.address"
                    placeholder="请输入地址"
                    clearable
                    @keyup.enter="handleQuery"
                    />
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item label="邮编" prop="postalCode">
                    <el-input
                    v-model="queryParams.postalCode"
                    placeholder="请输入邮编"
                    clearable
                    @keyup.enter="handleQuery"
                    />
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item label="网址" prop="website">
                    <el-input
                    v-model="queryParams.website"
                    placeholder="请输入网址"
                    clearable
                    @keyup.enter="handleQuery"
                    />
                </el-form-item>
            </el-col>
        </el-row>

        <el-row :gutter="20">
            <el-col :span="6">
                <el-form-item label="挂靠单位" prop="upUnitId">
                    <el-select v-model="queryParams.upUnitId" placeholder="请选择挂靠单位" clearable>
                        <el-option
                            v-for="dict in cfg_category_gkdw"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                        />
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item label="对应人事单位" prop="hrUnitId">
                    <el-select v-model="queryParams.hrUnitId" placeholder="请选择对应人事单位" clearable>
                        <el-option
                        v-for="dict in cfg_category_ssrsdw"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                        />
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item label="机构类别" prop="researchTypeId">
                    <el-select v-model="queryParams.researchTypeId" placeholder="请选择机构类别" clearable>
                    <el-option
                        v-for="dict in cfg_category_jglb"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                    />
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="6">
                
            </el-col>
        </el-row>

        <el-row :gutter="20">
            <el-col :span="6">
                <el-form-item label="主要技术领域" prop="techField">
                    <el-input
                    v-model="queryParams.techField"
                    placeholder="请输入主要技术领域"
                    clearable
                    @keyup.enter="handleQuery"
                    />
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item label="主要学科领域" prop="subjectField">
                    <el-input
                    v-model="queryParams.subjectField"
                    placeholder="请输入主要学科领域"
                    clearable
                    @keyup.enter="handleQuery"
                    />
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <!-- <el-form-item label="成立时间" prop="unitCreateDate" style="width:100%">
                    <el-date-picker clearable
                    v-model="queryParams.unitCreateDate"
                    type="date"
                    value-format="YYYY-MM-DD"
                    placeholder="请选择成立时间">
                    </el-date-picker>
                </el-form-item> -->
                <el-form-item label="成立时间" prop="daterangeUnitCreateDate" style="width: 100%">
                  <el-date-picker clearable
                    v-model="queryParams.daterangeUnitCreateDate"
                    value-format="YYYY-MM-DD"
                    type="daterange"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                  ></el-date-picker>
                </el-form-item>
            </el-col>
            <el-col :span="6">
                
            </el-col>
        </el-row>
        </div>
    </el-form>
    </el-card> 

    <el-card class="w-full mt-[20px]">  
    <el-row :gutter="10" class="mb8" v-if="getCurRole()!='biz_kyry'">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          @click="jumpCollect"
          v-hasPermi="['research:educationStat:list']"
        >教育部统计信息汇总</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['research:unit:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['research:unit:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['research:unit:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="unitList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="机构名称" align="center" prop="name" >
        <template v-slot="scope">  
          <div>
            <el-link type="primary" @click="handleView(scope.row)"> {{ scope.row.name }}  </el-link>
          </div>
        </template>  
      </el-table-column>
      <el-table-column label="机构编号" align="center" prop="code" />
      <el-table-column label="负责人" align="center" prop="charger" />
      <el-table-column label="机构级别" align="center" prop="levelId">
        <template #default="scope">
          <dict-tag :options="cfg_category_jgjb" :value="scope.row.levelId" :showSpan="true"/>
        </template>
      </el-table-column>
      <el-table-column label="机构人员 " align="center" prop="personNum" width="80">
        <template v-slot="scope">  
          <div>
            <el-link type="primary" @click="handlePerson(scope.row)">
              {{ scope.row.personNum ? scope.row.personNum : 0 }}
            </el-link>
          </div>
        </template>  
      </el-table-column>

      <el-table-column label="科研项目 " align="center" prop="projectNum" width="80">
        <template v-slot="scope">  
          <div>
            <el-link type="primary" @click="handleProject(scope.row)">
              {{ scope.row.projectNum ? scope.row.projectNum : 0  }}
            </el-link>
          </div>
        </template>  
      </el-table-column>

      <el-table-column label="科研成果 " align="center" prop="productNum" width="80">
        <template v-slot="scope">  
          <div>
            <el-link type="primary" @click="handleAchievement(scope.row)">
              {{ scope.row.productNum ? scope.row.productNum : 0  }}
            </el-link>
      </div>
        </template>  
      </el-table-column>

      <el-table-column label="科研获奖 " align="center" prop="honorNum" width="80">
        <template v-slot="scope">  
          <div>
            <el-link type="primary" @click="handleAward(scope.row)">
              {{ scope.row.honorNum ? scope.row.honorNum : 0  }}
            </el-link>
          </div>
        </template>  
      </el-table-column>

      <el-table-column label="审核状态" align="center" prop="checkStatus">
        <template #default="scope">
          <dict-tag :options="bpm_process_instance_status" :value="scope.row.checkStatus"/>
        </template>
      </el-table-column>
      <!-- <el-table-column label="审核时间" align="center" prop="checkDate" />
      <el-table-column label="审核人" align="center" prop="checker" />
      <el-table-column label="流程实例ID" align="center" prop="processInstanceId" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="getCurRole()!='biz_kyry'">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-if="(getCurRole()==='biz_kyms'&&scope.row.checkStatus!=='1')||(getCurRole()==='biz_kycgly')" v-hasPermi="['research:unit:edit']">编辑</el-button>
          <el-button link type="warning" icon="Edit" @click="revoke(scope.row)" v-if="(getCurRole()==='biz_kyms'&&scope.row.checkStatus==='1')&&(userStore.userRealId===scope.row.createUserId)" v-hasPermi="['research:unit:edit']">撤销</el-button>
          <el-button link type="success" icon="CircleCheck" @click="handleCheck(scope.row)" v-if="(getCurRole()==='biz_kycgly' && scope.row.checkStatus==='1')" v-hasPermi="['research:unit:check']">审核</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-if="(getCurRole()==='biz_kyms'&&scope.row.checkStatus!=='2'&&scope.row.checkStatus!=='1')||(getCurRole()==='biz_kycgly')" v-hasPermi="['research:unit:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    </el-card>  

    <UnitModal v-model:opType="opType" v-model:opUnitId="opUnitId" v-model="unitModalVisible" v-if="unitModalVisible" @refreshUnitList="onRefreshUnitList"/>

</template>

<script setup name="Research">
import cloneDeep from 'lodash/cloneDeep';  
import request from '@/utils/request'
import useUserStore from "@/store/modules/user";
import { listUnit, getCheckStatusCount, getUnit, delUnit, addUnit, updateUnit, getCategoryData, getCurRole} from "@/api/research/unit";
import { cancelProcessInstanceByStartUser }from "@/api/flowable/instance";

import UnitModal from "./components/UnitModal.vue";

const { proxy } = getCurrentInstance();
const { bpm_process_instance_status } = proxy.useDict('bpm_process_instance_status');
const userStore = useUserStore();

const cfg_category_jgjb = ref([]);
const cfg_category_jglb = ref([]);
const cfg_category_gkdw = ref([]);
const cfg_category_ssrsdw = ref([]);

const unitList = ref([]);
//const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
//const title = ref("");
const searchFormOpen = ref(false);

const opType = ref(0);
const opUnitId = ref(null);
const unitModalVisible = ref(false);

const checkStatusCount = ref({});

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    code: null,
    charger: null,
    contacts: null,
    hrUnitId: null,
    upUnitId: null,
    subjectClassId: null,
    subjectId: null,
    isSta: null,
    levelId: null,
    tel: null,
    fax: null,
    address: null,
    postalCode: null,
    email: null,
    website: null,
    fileIds: null,
    researchTypeId: null,
    approveDept: null,
    approveDate: null,
    isOpen: null,
    isCombined: null,
    techField: null,
    subjectField: null,
    intro: null,
    checkStatus: '',//null,
    checkDate: null,
    checker: null,
    createUserId: null,
    lastEditUserId: null,
    createDate: null,
    lastEditDate: null,
    createUserName: null,
    lastEditUserName: null,
    contactsId: null,
    chargerId: null,
    unitCheckDate: null,
    unitCreateDate: null,
    platformSummary: null,
    unitId: null,
    prevEvaluateTime: null,
    prevEvaluateResult: null,
    completeDataStatus: null,
    processInstanceId: null,

    daterangeUnitCreateDate: [],
  },
});

const { queryParams } = toRefs(data);

const saved = ref(null);

onMounted(() => {
    getCategoryData(cfg_category_jgjb, {bizName:"机构级别"}, true);
    getCategoryData(cfg_category_jglb, {bizName:"机构类别"}, true);
    getCategoryData(cfg_category_gkdw, {bizName:"挂靠单位"}, true);
    getCategoryData(cfg_category_ssrsdw, {bizName:"所属人事单位"}, true);
})

/** 查询科研平台-研究机构列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != queryParams.value.daterangeUnitCreateDate && '' != queryParams.value.daterangeUnitCreateDate) {
    queryParams.value.params["beginUnitCreateDate"] = queryParams.value.daterangeUnitCreateDate[0];
    queryParams.value.params["endUnitCreateDate"] = queryParams.value.daterangeUnitCreateDate[1];
  }
  listUnit(queryParams.value).then(response => {
    unitList.value = response.rows;
    total.value = response.total;
    loading.value = false;
    saved.value = cloneDeep(queryParams.value);
  });

  getCheckStatusCount(queryParams.value).then(response => {
    checkStatusCount.value = response.data;
    checkStatusCount.value.all = Object.values(checkStatusCount.value).reduce((sum,value)=>{return sum+value["checkStatusCount"]},0);
  });
}

function onRefreshUnitList(notClose) {
  if(!notClose){
    unitModalVisible.value = false;
  }
  resetQuery();
}

const router = useRouter();
function jumpCollect() {
  //proxy.$router.push("/research/educationStatCollect/index");
  router.push("/research/educationStatCollect/index");
};

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  //queryParams.daterangeUnitCreateDate = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
  opType.value = 0;
  opUnitId.value = null;
  unitModalVisible.value = true;
}

/** 编辑按钮操作 */
function handleUpdate(row) {
  opType.value = 1;
  opUnitId.value = row.id;
  unitModalVisible.value = true;
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('您确定要删除吗?').then(function() {
    return delUnit(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 撤销按钮操作 */
function revoke(row) {
  if (userStore.userRealId === row.createUserId) {
    proxy.$modal.confirm('您确定要撤销吗?').then(function() {
      return request({
        url: '/flowable/instance/cancel-by-start-user',
        method: 'delete',
        data: {id: row.processInstanceId, reason: "申请人主动撤销"}
      })
    }).then(() => {
      getList();
      proxy.$modal.msgSuccess("撤销成功");
    }).catch(() => {});
  }
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('research/unit/export', {
    ...queryParams.value
  }, `研究机构清单_${new Date().getTime()}.xlsx`)
}

//审核
function handleCheck(row) {
  opType.value = 2;
  opUnitId.value = row.id;
  unitModalVisible.value = true;
}

//查看
function handleView(row) {
  opType.value = 3;
  opUnitId.value = row.id;
  unitModalVisible.value = true;
}

function handlePerson(row) {
  proxy.$router.push({path: "/research/person/index", query:{researchUnitId: row.id}});
}

function handleProject(row) {
  proxy.$router.push({path: "/research/association/project", query:{researchUnitId: row.id}});
}

function handleAchievement(row) {
  proxy.$router.push({path: "/research/association/product", query:{researchUnitId: row.id}});
}

function handleAward(row) {
  proxy.$router.push({path: "/research/association/honor", query:{researchUnitId: row.id}});
}

onActivated(()=>{if(saved.value){queryParams.value=cloneDeep(saved.value);getList();}})
getList();
</script>

<style scoped lang="scss">
// @import url("@/views/research/index.scss");
</style>